package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.CutPageBean;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("add")
    private String add(@Valid UserBean userBean, BindingResult bindingResult) throws JsonProcessingException {
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            ObjectMapper objectMapper = new ObjectMapper();
            String error = objectMapper.writeValueAsString(errors);
            return error;
        }
        System.out.println(userBean);
        service.add(userBean);
        return "OK";
    }

    @RequestMapping("findByItem")
    public CutPageBean<UserBean> findByItem(Integer pageNO, String name, LocalDate startDate, LocalDate endDate) {
        return service.findByItem(pageNO, name, startDate, endDate);
    }
}
